﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IndoReputation.Models.BusinessLogic;
using Telerik.Web.Mvc;
using IndoReputation.Models.BusinessObject;
using IndoReputation.Views.ViewModels;
using IndoReputation.Commons;
using IndoReputation.Models.Constants;
using System.IO;
using Newtonsoft.Json;
using IndoReputation.Models.BusinessObject.Collections;

namespace IndoReputation.Controllers
{
    [Authorize]
    public class MediaController : BaseController
    {
        //
        // GET: /Media/

        public ActionResult Index()
        {
            ViewData["ajax"] = true;
            ViewData["scrolling"] = true;
            ViewData["paging"] = true;
            ViewData["filtering"] = true;
            ViewData["grouping"] = true;
            ViewData["sorting"] = true;
            ViewData["showFooter"] = true;
            return View();
        }

        [GridAction]
        public ActionResult _Index()
        {
            return View(new GridModel(MediaBOL.GetAllMediaJoin()));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _DeleteAjaxEditing(int id)
        {
            //Find a customer with ProductID equal to the id action parameter            
            if (id > 0)
            {
                //Delete the record        
                if (!MediaBOL.Delete(id))
                {
                    ModelState.AddModelError(String.Empty, @"This Media have new(s). Please check again!");
                }
            }

            //Rebind the grid
            return View(new GridModel(MediaBOL.GetAllMediaJoin()));
        }

        [HttpGet]
        public ActionResult Add()
        {
            ViewData["selectedDate"] =  DateTime.Today;
            var model = new MediaViewModel();
            model.MediaCategory = new SelectList(MediaCategoryBOL.GetAllMediaCategory(), "ID", "Name");
            model.Country = CountryBOL.GetAllCountry().Select(x => x.Name).ToList();
            model.City = CityBOL.GetAllCity().Select(x => x.Name).ToList();
            model.Freedom = CommonFunctions.ToSelectList<IRConstants.Choose>(new IRConstants.Choose());
            model.ViewerType = new SelectList(ViewerTypeBOL.GetAllViewerType(), "ID", "Name");
            model.OrientationType = new SelectList(OrientationTypeBOL.GetAllOrientationType(), "ID", "Name");
            model.OwnershipType = new SelectList(OwnershipTypeBOL.GetAllOwnershipType(), "ID", "Name");
            model.StrongInfluenceType = new SelectList(StrongInfluenceTypeBOL.GetAllStrongInfluenceType(), "ID", "Name");
            model.RankType = new SelectList(RankTypeBOL.GetAllRankType(), "ID", "Name");
            return View(model);
        }

        [HttpPost]
        public ActionResult Add(MediaViewModel model)
        {            
            if (ModelState.IsValid)
            {
                MediaCategoryShort deserializedMediaCategory = JsonConvert.DeserializeObject<MediaCategoryShort>(model.InputJsonMediaShort);
                Media media = new Media();
                media.AddBuildingName = (string.IsNullOrEmpty(model.AddBuildingName)) ? string.Empty : model.AddBuildingName.Trim();
                media.AddCity = (string.IsNullOrEmpty(model.AddCity)) ? string.Empty : model.AddCity.Trim().Remove(model.AddCity.Length - 1, 1);
                media.AddCountry = (string.IsNullOrEmpty(model.AddCountry)) ? string.Empty : model.AddCountry.Trim().Remove(model.AddCountry.Length - 1, 1);
                media.AddEmail = (string.IsNullOrEmpty(model.AddEmail)) ? string.Empty : model.AddEmail.Trim();
                media.AddFax = (string.IsNullOrEmpty(model.AddFax)) ? string.Empty : model.AddFax.Trim();
                media.AddPhone = (string.IsNullOrEmpty(model.AddPhone)) ? string.Empty : model.AddPhone.Trim();
                media.AddStreetName = (string.IsNullOrEmpty(model.AddStreetName)) ? string.Empty : model.AddStreetName.Trim();
                media.AddStreetNumber = (string.IsNullOrEmpty(model.AddStreetNumber)) ? string.Empty : model.AddStreetNumber.Trim();
                media.AddWebsite = (string.IsNullOrEmpty(model.AddWebsite)) ? string.Empty : model.AddWebsite.Trim();
                media.ChiefEditorEmail = (string.IsNullOrEmpty(model.ChiefEditorEmail))? string.Empty : model.ChiefEditorEmail.Trim();
                media.ChiefEditorMobile = (string.IsNullOrEmpty(model.ChiefEditorMobile)) ? string.Empty : model.ChiefEditorMobile.Trim();
                media.ChiefEditorName = (string.IsNullOrEmpty(model.ChiefEditorName)) ? string.Empty : model.ChiefEditorName.Trim();
                media.Description = (string.IsNullOrEmpty(model.Description)) ? string.Empty : model.Description.Trim();
                media.FirstTimeLaunched = model.FirstTimeLaunched;
                media.IsEnable = model.IsEnable;
                IRConstants.Choose x = CommonFunctions.StringToEnum<IRConstants.Choose>(model.StrFreedom);
                switch (x)
                {
                    case IRConstants.Choose.No:
                        media.IsFreedom = (byte)IRConstants.Choose.No;
                        break;
                    case IRConstants.Choose.NotSure:
                        media.IsFreedom = (byte)IRConstants.Choose.NotSure;
                        break;
                    case IRConstants.Choose.Yes:
                        media.IsFreedom = (byte)IRConstants.Choose.Yes;
                        break;
                    default:
                        break;
                }
                media.MediaCategoryID = model.MediaCategoryID;
                media.Name = model.Name.Trim();
                media.OrientationTypeID = model.OrientationTypeID;
                media.OwnershipTypeID = model.OwnershipTypeID;
                media.RankTypeID = model.RankTypeID;
                media.StrongInfluenceTypeID = model.StrongInfluenceTypeID;
                if (deserializedMediaCategory.IsNewspaper)
                    media.TotalPublishedDaily = model.TotalPublishedDaily;
                else
                    media.TotalPublishedDaily = null;
                if (deserializedMediaCategory.IsOnline)
                    media.TotalUsers = model.TotalUsers;
                else
                    media.TotalUsers = null;
                media.TotalViewersDaily = model.TotalViewersDaily;
                media.ViewerTypeID = model.ViewerTypeID;
                int mediaID = MediaBOL.Insert(media);
                if (model.ListReporter != null)
                {
                    if (model.ListReporter.Count > 0)
                    {
                        foreach (Reporter _r in model.ListReporter)
                        {
                            Reporter newReporter = new Reporter
                            {
                                Email = _r.Email,
                                FieldsConcerned = _r.FieldsConcerned,
                                Mobile = _r.Mobile,
                                Name = _r.Name
                            };
                            int reporterID = ReporterBOL.Insert(newReporter);
                            MediaReporter mediaReporter = new MediaReporter
                            {
                                MediaID = mediaID,
                                ReporterID = reporterID
                            };
                            MediaReporterBOL.Insert(mediaReporter);    
                        }
                    }
                }
            }
            else
            {                
                ViewData["selectedDate"] = DateTime.Today;               
                model.MediaCategory = new SelectList(MediaCategoryBOL.GetAllMediaCategory(), "ID", "Name");
                model.Country = CountryBOL.GetAllCountry().Select(x => x.Name).ToList();
                model.City = CityBOL.GetAllCity().Select(x => x.Name).ToList();
                model.Freedom = CommonFunctions.ToSelectList<IRConstants.Choose>(new IRConstants.Choose());
                model.ViewerType = new SelectList(ViewerTypeBOL.GetAllViewerType(), "ID", "Name");
                model.OrientationType = new SelectList(OrientationTypeBOL.GetAllOrientationType(), "ID", "Name");
                model.OwnershipType = new SelectList(OwnershipTypeBOL.GetAllOwnershipType(), "ID", "Name");
                model.StrongInfluenceType = new SelectList(StrongInfluenceTypeBOL.GetAllStrongInfluenceType(), "ID", "Name");
                model.RankType = new SelectList(RankTypeBOL.GetAllRankType(), "ID", "Name");
                return View(model);
            }
            //return View(model);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult Edit(int mediaID)
        {            
            Media media = MediaBOL.GetMediaById(mediaID);
            MediaViewModel model = new MediaViewModel();
            // Get General infor
            model.MediaCategory = new SelectList(MediaCategoryBOL.GetAllMediaCategory(), "ID", "Name");
            model.Country = CountryBOL.GetAllCountry().Select(x => x.Name).ToList();
            model.City = CityBOL.GetAllCity().Select(x => x.Name).ToList();
            model.Freedom = CommonFunctions.ToSelectList<IRConstants.Choose>(new IRConstants.Choose());
            model.ViewerType = new SelectList(ViewerTypeBOL.GetAllViewerType(), "ID", "Name");
            model.OrientationType = new SelectList(OrientationTypeBOL.GetAllOrientationType(), "ID", "Name");
            model.OwnershipType = new SelectList(OwnershipTypeBOL.GetAllOwnershipType(), "ID", "Name");
            model.StrongInfluenceType = new SelectList(StrongInfluenceTypeBOL.GetAllStrongInfluenceType(), "ID", "Name");
            model.RankType = new SelectList(RankTypeBOL.GetAllRankType(), "ID", "Name");
            model.AddBuildingName = media.AddBuildingName;
            model.AddCity = media.AddCity;
            model.AddCountry = media.AddCountry;
            model.AddEmail = media.AddEmail;
            model.AddFax = media.AddFax;
            model.AddPhone = media.AddPhone;
            model.AddStreetName = media.AddStreetName;
            model.AddStreetNumber = media.AddStreetNumber;
            model.AddWebsite = media.AddWebsite;
            model.ChiefEditorEmail = media.ChiefEditorEmail;
            model.ChiefEditorMobile = media.ChiefEditorMobile;
            model.ChiefEditorName = media.ChiefEditorName;
            model.CreateAt = media.CreateAt;
            model.CreateBy = media.CreateBy;
            model.Description = media.Description;
            model.FirstTimeLaunched = media.FirstTimeLaunched;
            ViewData["selectedDate"] = media.FirstTimeLaunched;
            model.ID = media.ID;
            model.IsEnable = media.IsEnable ?? false;
            model.IsFreedom = media.IsFreedom;
            model.MediaCategoryID = media.MediaCategoryID;
            model.Name = media.Name;
            model.OrientationTypeID = media.OrientationTypeID;
            model.OwnershipTypeID = media.OwnershipTypeID;
            model.RankTypeID = media.RankTypeID;
            model.StrongInfluenceTypeID = media.StrongInfluenceTypeID;
            model.TotalPublishedDaily = media.TotalPublishedDaily;
            model.TotalUsers = media.TotalUsers;
            model.TotalViewersDaily = media.TotalViewersDaily;
            model.ViewerTypeID = media.ViewerTypeID;
            switch (Convert.ToInt32(media.IsFreedom))
            {
                case (int)IRConstants.Choose.No:
                    model.StrFreedom = IRConstants.Choose.No.ToString();
                    break;
                case (int)IRConstants.Choose.NotSure:
                    model.StrFreedom = IRConstants.Choose.NotSure.ToString();
                    break;
                case (int)IRConstants.Choose.Yes:
                    model.StrFreedom = IRConstants.Choose.Yes.ToString();
                    break;
                default:
                    break;
            }
            // Get Reporter
            model.ListReporter = ReporterBOL.GetAllReporterByMediaID(mediaID);
            ReporterList listReportOrg = new ReporterList();
            foreach (Reporter _r in model.ListReporter)
                listReportOrg.Add(_r);
            model.ListReporterOrginalString = JsonConvert.SerializeObject(listReportOrg);
            // Get InputJsonMediaShort
            model.InputJsonMediaShort = JsonConvert.SerializeObject(MediaCategoryBOL.GetMediaCategoryShortById(model.MediaCategoryID));
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(MediaViewModel model)
        {
            if (ModelState.IsValid)
            {
                // update Media
                MediaCategoryShort deserializedMediaCategory = JsonConvert.DeserializeObject<MediaCategoryShort>(model.InputJsonMediaShort);
                ReporterList listReportOrg = JsonConvert.DeserializeObject<ReporterList>(model.ListReporterOrginalString);
                List<Reporter> ListReporterOrginal = new List<Reporter>();
                if (listReportOrg != null)
                {
                    if (listReportOrg.Count > 0)
                    {
                        foreach (Reporter _r in listReportOrg)
                        {
                            ListReporterOrginal.Add(_r);
                        }
                    }
                }
                Media media = new Media();
                media.ID = model.ID;
                media.CreateAt = model.CreateAt;
                media.CreateBy = model.CreateBy;                
                media.AddBuildingName = (string.IsNullOrEmpty(model.AddBuildingName)) ? string.Empty : model.AddBuildingName.Trim();
                if (string.IsNullOrEmpty(model.AddCity))
                    media.AddCity = string.Empty;
                else
                {
                    if (model.AddCity[model.AddCity.Length - 1] == ',')                    
                        media.AddCity = model.AddCity.Trim().Remove(model.AddCity.Length - 1, 1);                    
                    else
                        media.AddCity = model.AddCity;
                }
                if (string.IsNullOrEmpty(model.AddCountry))
                    media.AddCountry = string.Empty;
                else
                {
                    if (model.AddCountry[model.AddCountry.Length - 1] == ',')
                        media.AddCountry = model.AddCountry.Trim().Remove(model.AddCountry.Length - 1, 1);
                    else
                        media.AddCountry = model.AddCountry;
                }
                media.AddEmail = (string.IsNullOrEmpty(model.AddEmail)) ? string.Empty : model.AddEmail.Trim();
                media.AddFax = (string.IsNullOrEmpty(model.AddFax)) ? string.Empty : model.AddFax.Trim();
                media.AddPhone = (string.IsNullOrEmpty(model.AddPhone)) ? string.Empty : model.AddPhone.Trim();
                media.AddStreetName = (string.IsNullOrEmpty(model.AddStreetName)) ? string.Empty : model.AddStreetName.Trim();
                media.AddStreetNumber = (string.IsNullOrEmpty(model.AddStreetNumber)) ? string.Empty : model.AddStreetNumber.Trim();
                media.AddWebsite = (string.IsNullOrEmpty(model.AddWebsite)) ? string.Empty : model.AddWebsite.Trim();
                media.ChiefEditorEmail = (string.IsNullOrEmpty(model.ChiefEditorEmail)) ? string.Empty : model.ChiefEditorEmail.Trim();
                media.ChiefEditorMobile = (string.IsNullOrEmpty(model.ChiefEditorMobile)) ? string.Empty : model.ChiefEditorMobile.Trim();
                media.ChiefEditorName = (string.IsNullOrEmpty(model.ChiefEditorName)) ? string.Empty : model.ChiefEditorName.Trim();
                media.Description = (string.IsNullOrEmpty(model.Description)) ? string.Empty : model.Description.Trim();
                media.FirstTimeLaunched = model.FirstTimeLaunched;
                media.IsEnable = model.IsEnable;
                IRConstants.Choose x = CommonFunctions.StringToEnum<IRConstants.Choose>(model.StrFreedom);
                switch (x)
                {
                    case IRConstants.Choose.No:
                        media.IsFreedom = (byte)IRConstants.Choose.No;
                        break;
                    case IRConstants.Choose.NotSure:
                        media.IsFreedom = (byte)IRConstants.Choose.NotSure;
                        break;
                    case IRConstants.Choose.Yes:
                        media.IsFreedom = (byte)IRConstants.Choose.Yes;
                        break;
                    default:
                        break;
                }
                media.MediaCategoryID = model.MediaCategoryID;
                media.Name = model.Name.Trim();
                media.OrientationTypeID = model.OrientationTypeID;
                media.OwnershipTypeID = model.OwnershipTypeID;
                media.RankTypeID = model.RankTypeID;
                media.StrongInfluenceTypeID = model.StrongInfluenceTypeID;
                if (deserializedMediaCategory.IsNewspaper)
                    media.TotalPublishedDaily = model.TotalPublishedDaily;
                else
                    media.TotalPublishedDaily = null;
                if (deserializedMediaCategory.IsOnline)
                    media.TotalUsers = model.TotalUsers;
                else
                    media.TotalUsers = null;
                media.TotalViewersDaily = model.TotalViewersDaily;
                media.ViewerTypeID = model.ViewerTypeID;
                MediaBOL.Update(media);
                // update Reporter
                // case 1 : delete all
                if (model.ListReporter == null)
                {
                    if (ListReporterOrginal != null)
                    {
                        if (ListReporterOrginal.Count > 0)
                        {
                            foreach (Reporter _r in ListReporterOrginal)
                            {                                
                                MediaReporterBOL.Delete(model.ID, _r.ID);
                            }
                        }
                    }
                }
                // add new or update
                if (model.ListReporter != null)
                {
                    if (model.ListReporter.Count > 0)
                    {
                        // find new reporter to insert
                        List<Reporter> listNewReporter = model.ListReporter.Where(m => m.ID == 0).ToList();
                        if (listNewReporter != null)
                        {
                            if (listNewReporter.Count > 0)
                            {
                                foreach (Reporter _r in listNewReporter)
                                {
                                    Reporter newReporter = new Reporter
                                    {
                                        Email = _r.Email,
                                        FieldsConcerned = _r.FieldsConcerned,
                                        Mobile = _r.Mobile,
                                        Name = _r.Name
                                    };
                                    int reporterID = ReporterBOL.Insert(newReporter);
                                    MediaReporter mediaReporter = new MediaReporter
                                    {
                                        MediaID = model.ID,
                                        ReporterID = reporterID
                                    };
                                    MediaReporterBOL.Insert(mediaReporter);
                                }
                            }
                        }
                        List<Reporter> listOldReporter = model.ListReporter.Where(m => m.ID != 0).ToList() ?? new List<Reporter>();
                        if (ListReporterOrginal != null)
                        {
                            if (ListReporterOrginal.Count > 0)
                            {
                                // delete all
                                if (listOldReporter.Count == 0)
                                {
                                    foreach (Reporter _r in ListReporterOrginal)
                                    {
                                        MediaReporterBOL.Delete(model.ID, _r.ID);
                                    }
                                }
                                else if (listOldReporter.Count > 0)
                                {
                                    for (int i = 0; i < ListReporterOrginal.Count; i++)
                                    {
                                        bool isExist = false;
                                        Reporter reporterTemp = new Reporter();
                                        for (int j = 0; j < listOldReporter.Count; j++)
                                        {
                                            if (listOldReporter[j].ID == ListReporterOrginal[i].ID)
                                            {
                                                isExist = true;
                                                if (listOldReporter[j].Email != ListReporterOrginal[i].Email || listOldReporter[j].FieldsConcerned != ListReporterOrginal[i].FieldsConcerned || listOldReporter[j].Mobile != ListReporterOrginal[i].Mobile || listOldReporter[j].Name != ListReporterOrginal[i].Name)
                                                {
                                                    reporterTemp.ID = listOldReporter[j].ID;
                                                    reporterTemp.CreateAt = listOldReporter[j].CreateAt;
                                                    reporterTemp.CreateBy = listOldReporter[j].CreateBy;
                                                    reporterTemp.Email = listOldReporter[j].Email;
                                                    reporterTemp.FieldsConcerned = listOldReporter[j].FieldsConcerned;
                                                    reporterTemp.Mobile = listOldReporter[j].Mobile;
                                                    reporterTemp.Name = listOldReporter[j].Name;
                                                }
                                                break;
                                            }
                                        }
                                        // update reporter infor
                                        if (isExist)
                                        {
                                            if (reporterTemp.ID > 0)
                                                ReporterBOL.Update(reporterTemp);
                                        }
                                        // delete
                                        else
                                        {
                                            MediaReporterBOL.Delete(model.ID, ListReporterOrginal[i].ID);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                ViewData["selectedDate"] = model.FirstTimeLaunched;
                model.MediaCategory = new SelectList(MediaCategoryBOL.GetAllMediaCategory(), "ID", "Name");
                model.Country = CountryBOL.GetAllCountry().Select(x => x.Name).ToList();
                model.City = CityBOL.GetAllCity().Select(x => x.Name).ToList();
                model.Freedom = CommonFunctions.ToSelectList<IRConstants.Choose>(new IRConstants.Choose());
                model.ViewerType = new SelectList(ViewerTypeBOL.GetAllViewerType(), "ID", "Name");
                model.OrientationType = new SelectList(OrientationTypeBOL.GetAllOrientationType(), "ID", "Name");
                model.OwnershipType = new SelectList(OwnershipTypeBOL.GetAllOwnershipType(), "ID", "Name");
                model.StrongInfluenceType = new SelectList(StrongInfluenceTypeBOL.GetAllStrongInfluenceType(), "ID", "Name");
                model.RankType = new SelectList(RankTypeBOL.GetAllRankType(), "ID", "Name");
                return View(model);
            }            
            return RedirectToAction("Index");
        }

        [HttpPost]
        public JsonResult _GetMediaCategoryShort(int? mediaCategoryID)
        {
            MediaCategoryShort media = new MediaCategoryShort();
            if (mediaCategoryID.HasValue)
            {
                media = MediaCategoryBOL.GetMediaCategoryShortById(mediaCategoryID ?? 0);
            }
            return Json(media, JsonRequestBehavior.AllowGet);
        }

        //protected string RenderPartialViewToString(string viewName, object model)
        //{
        //    if (string.IsNullOrEmpty(viewName))
        //        viewName = ControllerContext.RouteData.GetRequiredString("action");

        //    ViewData.Model = model;

        //    using (StringWriter sw = new StringWriter())
        //    {
        //        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        //        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        //        viewResult.View.Render(viewContext, sw);

        //        return sw.GetStringBuilder().ToString();
        //    }
        //}

        [HttpPost]
        public ActionResult AddNewReport()
        {
            return PartialView("~/Views/Shared/EditorTemplates/Reporter.cshtml", new Reporter());
        }        
    }
}
